package com.azt.front.service.impl;

import com.azt.api.pojo.Area;
import com.azt.api.pojo.UserFunction;
import com.azt.api.service.AreaService;
import com.azt.api.service.FunctionService;
import com.azt.front.service.RedisService;
import com.azt.front.utils.Globals;
import com.xiaoleilu.hutool.util.CollectionUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Redis操作Service
 * Created by shangwq on 2016/11/17.
 */
@Service
public class RedisServiceImpl implements RedisService {

    private static final Logger LOGGER = Logger.getLogger(RedisServiceImpl.class);

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AreaService areaService;

    @Autowired
    private FunctionService functionService;

    @Override
    public List<Area> findAllArea() {
        List<Area> areaList = null;
        try {
            BoundListOperations ops =  redisTemplate.boundListOps(Globals.AREA_REDIS_KEY);
            areaList = (List<Area>) ops.range(0, ops.size() - 1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(CollectionUtil.isEmpty(areaList)) {
            areaList = areaService.findAllArea();
        }
        return areaList;
    }

    @Override
    public Area getArea(String code) {
        List<Area> areaList = findAllArea();
        if(CollectionUtil.isNotEmpty(areaList)) {
            for(Area area : areaList) {
                if(StrUtil.equals(area.getCode(), code)) {
                    return area;
                }
            }
        }
        return null;
    }

    @Override
    public List<UserFunction> findAllFunc() {
        List<UserFunction> funcList = null;
        try {
            BoundListOperations ops =  redisTemplate.boundListOps(Globals.FUNCTION_REDIS_KEY);
            funcList = (List<UserFunction>) ops.range(0, ops.size() - 1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(CollectionUtil.isEmpty(funcList)) {
            funcList = functionService.findAllFunc();
        }
        return funcList;
    }
}
